import { useEffect, useRef } from 'react';
import { useProjectStore, useEditorStore } from '../stores';
import { useOutputHandler } from './useOutputHandler';
import globalEventManager, { PYTHON_EVENTS, PROJECT_EVENTS } from '../utils/eventManager';

export const usePythonPlayer = () => {
  const projectStore = useProjectStore();
  const editorStore = useEditorStore();
  const { outputListener } = useOutputHandler();
  const editorRef = useRef(null);
  const isProjectInitialized = useRef(false);
  const isEditorReady = useRef(false);

  // 尝试加载文件内容到编辑器
  const loadFileToEditor = async () => {
    if (isProjectInitialized.current && isEditorReady.current) {
      try {
        await projectStore.loadCurrentFileToEditor();
      } catch (error) {
        console.error('加载文件内容到编辑器失败:', error);
      }
    }
  };

  useEffect(() => {
    // 输出事件监听
    const unsubscribeOutput = globalEventManager.on(PYTHON_EVENTS.OUTPUT, outputListener);

    // 错误处理事件监听
    const unsubscribeError = globalEventManager.on(PYTHON_EVENTS.ERROR, (errorInfo) => {
      if (errorInfo.line && editorRef.current) {
        editorStore.highlightErrorLine(errorInfo.line, errorInfo.type, editorRef.current);
      }
    });

    // 运行开始时清除错误高亮
    const unsubscribeStatusChange = globalEventManager.on(PYTHON_EVENTS.STATUS_CHANGE, (status) => {
      if (status === 'running' && editorRef.current) {
        editorStore.clearErrorHighlight(editorRef.current);
      }
    });


    // 监听项目初始化完成事件
    const unsubscribeProjectInitialized = globalEventManager.on(PROJECT_EVENTS.INITIALIZED, async () => {
      isProjectInitialized.current = true;
      await loadFileToEditor();
    });

    // 初始化项目
    const initializeProject = async () => {
      try {
        const unsubscribe = await projectStore.initializeEventSubscriptions();
        await projectStore.initializeProject();
        return unsubscribe;
      } catch (error) {
        console.error('项目初始化失败:', error);
        return null;
      }
    };

    let unsubscribeProjectEvents = null;
    initializeProject().then((unsubscribe) => {
      unsubscribeProjectEvents = unsubscribe;
    });

    // 清理函数
    return () => {
      unsubscribeOutput();
      unsubscribeError();
      unsubscribeStatusChange();
      unsubscribeProjectInitialized();
      if (unsubscribeProjectEvents) {
        unsubscribeProjectEvents();
      }
    };
  }, []);

  const handleEditorReady = async (editor) => {
    editorRef.current = editor;
    isEditorReady.current = true;
    
    // 编辑器准备好后，尝试加载文件内容
    await loadFileToEditor();
  };

  return { 
    handleEditorReady,
    editorRef
  };
};
